package net.pulseproject.router.modules.useable;

import java.util.Collection;

import javax.sound.midi.ShortMessage;

import net.pulseproject.commons.midi.Receivable;
import net.pulseproject.commons.midi.Transmitable;
import net.pulseproject.commons.util.MidiUtil;
import net.pulseproject.router.modules.BiDirectionalModule;
import net.pulseproject.router.modules.logic.ValueAveragerImpl;
import net.pulseproject.router.modules.logic.ValueModifier;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class SimpleMergerModule extends BiDirectionalModule {
	
	private static final Log LOG = LogFactory.getLog(SimpleMergerModule.class);
	
	private final ValueModifier<Transmitable> averager;
	
	// TODO inject ValueAverager! +++ rewrite unit test (only module test, and separate only ValueAverager test)
	public SimpleMergerModule(final String id, final Collection<Receivable> outgoingModules, final int fanIn) {
		super(id, outgoingModules);
		LOG.debug("new SimpleMergerModule(id=[" + id + "], outgoingModules, fanIn=" + fanIn + ")");
		this.averager = new ValueAveragerImpl<Transmitable>(fanIn);
	}
	
	@Override
	public final void receive(final ShortMessage message, final Transmitable transmitable) {
		LOG.trace("receive(message, transmitable)");
		
		final int newData2 = this.averager.calculateValue(transmitable, message.getData2());
		final ShortMessage newMessage = MidiUtil.deriveMessageByData2(message, newData2);
		
		this.broadcastToOutgoingModules(newMessage);
	}

}
